﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using Microsoft.VisualBasic;
using System.Windows.Forms;

namespace HBAClient
{
    public partial class Banks : Form
    {
        private string strBankName;
        private int nMonthsBack = 2;
        private int nPlanMonthsBack = 2;
        private int nPlanMonthsForward = 2;
        public Banks(string BankNameGivven)
        {
            strBankName = BankNameGivven;
            InitializeComponent();
        }

		private void Banks_Load(object sender, EventArgs e)
		{
            AdvancePlan();

            txtPlanIn.Text = "0";
            txtPlanOut.Text = "0";
            lblBankYear.Text = "Today: " + DateTime.Now.ToShortDateString();
            lblBankName.Text = "Bank/Credit Card: " + strBankName;
            txtMonthsBack.Text = nMonthsBack.ToString();
            txtPlanBack.Text = nPlanMonthsBack.ToString();
            txtPlanForward.Text = nPlanMonthsForward.ToString();
            txtResetYear.Text = DateTime.Now.AddMonths(1).Year.ToString();
            txtResetDay.Text = "10";
            txtResetMonth.Text = DateTime.Now.AddMonths(1).Month.ToString();
            lblBankMsg.Text = Util.DEFAULT_BANK_MSG;
            dtEpirationChoose.Value = Util.EXPIRATION_DATE;
            // Set sources
            Util.SetSources(ref cmbPlanSource);
            Util.SetReoccurrences(ref cmbPlanReoccurrence);
            

            SetBankGrid();
            SetPlansGrid();

            DoRefreshSumPlan();
		}
        private void AdvancePlan()
        {
            //HBADBDataContext db = new HBADBDataContext();
            using (HBADBDataContext db = new HBADBDataContext())
            {
                int nRecordsTransferCount = 0;
                foreach (var record in db.Plans)
                {
                    if (record.Date < new DateTime(DateTime.Now.Year, DateTime.Now.Month,1, 0, 0, 0) &&
                        record.UserID == Program.GetUserID() &&
                        record.BankID == Util.GetNewBankID(strBankName) &&
                        record.Closed == Util.PLAN_NOT_CLOSED)
                    {
                        nRecordsTransferCount++;
                        record.Date = new DateTime(DateTime.Now.Year, DateTime.Now.Month, 1, 0, 0, 10);
                    }
                    
                }
                if (nRecordsTransferCount > 0)
                {
                    DialogResult dl = MessageBox.Show("Found " + nRecordsTransferCount + 
                        " plan records to transfer to 1/1. Do transfer?", "Transfer plan records",
                       MessageBoxButtons.OKCancel);

                    if (dl == DialogResult.OK)
                    {
                        db.SubmitChanges();
                    }
                }
            }

            //Plan toUpdate = db.Plans.SelectMany(p => p.Date < new DateTime(DateTime.Now.Year, DateTime.Now.Month,
              //  1, 0, 0, 0));
            //= new DateTime(DateTime.Now.Year, DateTime.Now.Month,1, 0, 0, 10);

        }
        private void SetPlansGrid()
        {
            HBADBDataContext db = new HBADBDataContext();
            int nMonthsBack = nPlanMonthsBack;
            int nMonthForward = nPlanMonthsForward;
            if (!int.TryParse(txtPlanBack.Text,out nMonthsBack)) // bad
            {
                nMonthsBack = nPlanMonthsBack;
            }

            if (!int.TryParse(txtPlanForward.Text,out nMonthForward)) // bad
            {
                nMonthForward = nPlanMonthsForward;
            }
           
            //try
            //{
            //    nMonthsBack = Decimal.Parse(txtMonthsBack.Text);
            //}
            //catch
            //{
            //    nMonthsBack = 2;
            //}

            var query = from plan in db.Plans
                        join bank in db.Banks on plan.BankID equals bank.BankID
                        where plan.UserID == Program.GetUserID() && plan.Date >= DateTime.Now.AddMonths(-nMonthsBack) &&
                        plan.Date <= DateTime.Now.AddMonths(nMonthForward) && bank.BankName == strBankName
                        select new
                        {
                            //BankName = bank.BankName,
                            //PlanID = plan.PlanID,
                            Date = plan.Date,
                            Source = plan.Source,
                            InSum = plan.InSum,
                            OutSum = plan.OutSum,
                            Reoccurrence = plan.Reoccurrence,
                            Closed = plan.Closed,
                            PlanIndx = plan.PlanID
                        };

            dgvPlans.DataSource = query.OrderBy(x => x.Date);
            lblBankMsg.ForeColor = Color.Green;
        }
        private void SetBankGrid()
        {
            HBADBDataContext db = new HBADBDataContext();

            try
            {
                nMonthsBack = int.Parse(txtMonthsBack.Text);
            }
            catch
            {
                nMonthsBack = 2;
            }

            var query = from bill in db.Bills
                        join bank in db.Banks on bill.BankID equals bank.BankID
                        where bill.UserID == Program.GetUserID() &&
                        bill.Date >= DateTime.Now.AddMonths(-nMonthsBack) && 
                        bill.Date <= DateTime.Now.AddMonths(+nMonthsBack) &&
                        bank.BankName == strBankName
                        select new
                        {
                            BillID = bill.BillID,
                            //BankName = bank.BankName,
                            Date = bill.Date,
                            Source = bill.Source,
                            InSum = bill.InSum,
                            OutSum = bill.OutSum,
                            Balance = bill.Balance
                        };


            dgvBanks.DataSource = query.OrderBy(x => x.Date);
            //dgvBanks.DataSource = query.OrderBy(x => x.BillID).OrderBy(x => x.Date);
            dgvBanks.Refresh();
            
            lblBankMsg.ForeColor = Color.Green;
            // Set collors
            //SetCollors();
        }

        private void SetCollors()
        {
            if (btnShowReset.Text.ToUpper() == "Show Reset".ToUpper())
            {
                btnShowReset.Text = "Hide Reset";

                for (int i = 0; i < dgvBanks.Rows.Count; i++)
                {
                    if (dgvBanks.Rows[i].Cells[2].Value.ToString().ToUpper() == "RESET")
                    {
                        dgvBanks.Rows[i].Cells[0].Style.BackColor = Color.Gray;
                        dgvBanks.Rows[i].Cells[1].Style.BackColor = Color.Gray;
                        dgvBanks.Rows[i].Cells[2].Style.BackColor = Color.Gray;
                        dgvBanks.Rows[i].Cells[3].Style.BackColor = Color.Gray;
                        dgvBanks.Rows[i].Cells[4].Style.BackColor = Color.Gray;
                        dgvBanks.Rows[i].Cells[5].Style.BackColor = Color.Gray;
                        //dgvBanks.Rows[i].Cells[6].Style.BackColor = Color.Gray;
                    }
                }
            }
            else
            {
                btnShowReset.Text = "Show Reset";
                for (int i = 0; i < dgvBanks.Rows.Count; i++)
                {
                    dgvBanks.Rows[i].Cells[0].Style.BackColor = Color.White;
                    dgvBanks.Rows[i].Cells[1].Style.BackColor = Color.White;
                    dgvBanks.Rows[i].Cells[2].Style.BackColor = Color.White;
                    dgvBanks.Rows[i].Cells[3].Style.BackColor = Color.White;
                    dgvBanks.Rows[i].Cells[4].Style.BackColor = Color.White;
                    dgvBanks.Rows[i].Cells[5].Style.BackColor = Color.White;
                }
            }
        }

        private void btnClose_Click(object sender, EventArgs e)
        {
            this.Close();
        }

        private void btnDelBill_Click(object sender, EventArgs e)
        {
            try
            {
                string strBillID_ToDelete = dgvBanks.SelectedCells[0].Value.ToString();
                DialogResult dl = MessageBox.Show("Are you sure you want to delete the record with BillID " +
                     strBillID_ToDelete  + "?", "Delete a record",
                    MessageBoxButtons.OKCancel);

                if (dl == DialogResult.OK)
                {
                    Util.DeleteBillRecord(Convert.ToInt64(strBillID_ToDelete));

                    lblBankMsg.Text = "Delete record is successfully";
                    SetBankGrid();
                }
            }
            catch
            {
                lblBankMsg.Text = "Delete record is failed";
                lblBankMsg.ForeColor = Color.Red;
            }

            
        }

        private void btnRefresh_Click(object sender, EventArgs e)
        {
            SetBankGrid();
        }

        private void btnResetCredit_Click(object sender, EventArgs e)
        {
            
            DialogResult dl = MessageBox.Show("Are you sure you want to reset the Credit Card? ","Reset Credit Card",
                    MessageBoxButtons.OKCancel);

            if (dl == DialogResult.OK)
            {
                DateTime dtDateToReset = new DateTime(int.Parse(txtResetYear.Text), int.Parse(txtResetMonth.Text), int.Parse(txtResetDay.Text),
                    0, 0, 0);

                //dtDateToReset = dtDateToReset.AddMonths(1);

                // Get the latest balance for the date
                Decimal nLastBalance = Util.GetLastBalanceByDate(Program.GetUserID(), Util.GetNewBankID(strBankName), dtDateToReset);

                // Insert record with reseting values
                // Insert the bill record
                //dtDateToReset = dtDateToReset.AddDays(-1);
                //dtDateToReset = dtDateToReset.AddHours(22).AddMinutes(58).AddSeconds(58);
                SaveClick(Math.Abs(nLastBalance), dtDateToReset);

                // Reorder the balances in the bills and get the last balance
                Decimal nFinalBalance = Util.RunOrderBills(Program.GetUserID(), Util.GetNewBankID(strBankName));
                // Update balances table with the last balance
                Util.SaveNewBalance(Program.GetUserID(), Util.GetNewBankID(strBankName), nFinalBalance);
                
                // Refreshing the table
                SetBankGrid();
            }

            
        }

        // Insert new bill record
        private void SaveClick(Decimal SumToInsert, DateTime dtInsertDate)
        {
            try
            {
                // Invoke the save bill record function
                Util.SaveRecord(Program.GetUserID(), dtInsertDate, SumToInsert, 0,
                    Util.GetNewBankID(strBankName), "Reset");
                lblBankMsg.Text = "Reset Saved successfully";
            }
            catch
            {
                lblBankMsg.Text = "Reset Unable to save";
            }
        }

        private void button1_Click(object sender, EventArgs e)
        {
            SetCollors();
        }

        private void btnPlanOpt_Click(object sender, EventArgs e)
        {

        }

        private void chkBankOpt_CheckedChanged(object sender, EventArgs e)
        {
            if (chkBankOpt.Checked) // Show
            {
                pnlBankDel.Visible = true;
                pnlBank.Visible = true;
            }
            else // Hide
            {
                pnlBankDel.Visible = false;
                pnlBank.Visible = false;
            }
        }

        private void chkCreditOpt_CheckedChanged(object sender, EventArgs e)
        {
            if (chkCreditOpt.Checked) // Show
            {
                pnlResetCredit.Visible = true;
                pnlCreditCards.Visible = true;
            }
            else // Hide
            {
                pnlResetCredit.Visible = false;
                pnlCreditCards.Visible = false;
            }
        }

        private void chkPlanOpt_CheckedChanged(object sender, EventArgs e)
        {
            if (chkPlanOpt.Checked) // Show
            {
                pnlPlanBack.Visible = true;
                pnlPlan.Visible = true;

                dtEpirationChoose.Value = Util.EXPIRATION_DATE;
            }
            else // Hide
            {
                pnlPlanBack.Visible = false;
                pnlPlan.Visible = false;
            }
        }

        private void btnPlanSave_Click(object sender, EventArgs e)
        {
            try
            {
                 DialogResult dl = MessageBox.Show("Are you sure you want to save the plan record?",
                        "Save a record",
                        MessageBoxButtons.OKCancel);

                 if (dl == DialogResult.OK)
                 {

                     // Check validation
                     bool bValid = true;
                     string strinvalidMessage = "NoMessage";
                     Decimal nPlanOut = 0;
                     Decimal nPlanIn = 0;

                     if (String.IsNullOrEmpty(txtPlanOut.Text))
                     {
                         txtPlanOut.Text = "0";
                     }

                     if (String.IsNullOrEmpty(txtPlanIn.Text))
                     {
                         txtPlanIn.Text = "0";
                     }

                     if (dtPlanDate.Value < new DateTime(DateTime.Now.Year, 1, 1)) // Date not valid
                     {
                         bValid = false;
                         strinvalidMessage = "Plan date must be bigger (equal) than beginning of current month.";
                     }
                     else if (dtPlanDate.Value >= dtEpirationChoose.Value) // Date not valid
                     {
                         bValid = false;
                         strinvalidMessage = "Expiration date must be bigger than the plan date.";
                     }
                     else if (String.IsNullOrEmpty(cmbPlanSource.Text))
                     {
                         bValid = false;
                         strinvalidMessage = "Source is empty.";
                     }
                     else if (!Decimal.TryParse(txtPlanOut.Text, out nPlanOut))
                     {
                         bValid = false;
                         strinvalidMessage = "Out text box must be a number.";
                     }
                     else if (!Decimal.TryParse(txtPlanIn.Text, out nPlanIn))
                     {
                         bValid = false;
                         strinvalidMessage = "In text box must be a number.";
                     }
                     else if (cmbPlanReoccurrence.SelectedIndex < 0)
                     {
                         bValid = false;
                         strinvalidMessage = "Please choose reoccurrence.";
                     }
                     else if (String.IsNullOrEmpty(cmbPlanReoccurrence.Text))
                     {
                         bValid = false;
                         strinvalidMessage = "Please choose reoccurrence.";
                     }

                     if (bValid) // All fields are valid
                     {

                         string strResultSave = Util.SavePlan(strBankName, dtPlanDate.Value, cmbPlanSource.Text,
                             nPlanOut, nPlanIn, cmbPlanReoccurrence.Text, dtEpirationChoose.Value);
                         if (strResultSave != "")
                         {
                             lblBankMsg.Text = strResultSave;
                             SetPlansGrid();
                         }
                         // Message of success on save
                     }
                     else // Not valid for save
                     {
                         throw new Exception("Cant save new plan. Message: " + strinvalidMessage);
                     }
                 }
            }
            catch (Exception ex)
            {
                lblBankMsg.Text = ex.Message;
                lblBankMsg.ForeColor = Color.Red;
            }
        }

        private void btnRefreshPlan_Click(object sender, EventArgs e)
        {
            SetPlansGrid();
        }

        private void btnPlanDel_Click(object sender, EventArgs e)
        {
            try
            {
                if (dgvPlans.SelectedRows.Count == 1) // Have selected plan for delete
                {
                    //long lPlanIDTo_Delete = long.Parse(dgvPlans.SelectedCells[0].Value.ToString());
                    //string strPlanID_ToDelete = lPlanIDTo_Delete.ToString();
                    DialogResult dl = MessageBox.Show("Are you sure you want to delete a plan record?",
                        "Delete a record",
                        MessageBoxButtons.OKCancel);

                    if (dl == DialogResult.OK)
                    {
                        if (ValidatePlanToDelete())
                        {
                            // Check if the plan record opened
                            string strRecordOpenClosed = (string)dgvPlans.SelectedCells[5].Value.ToString();
                            if (strRecordOpenClosed.ToUpper() == Util.PLAN_NOT_CLOSED) // Plan not closed
                            {
                                int nRecordsDeleted = Util.DeletePlanRecord(strBankName, dtPlanDate.Value, cmbPlanSource.Text,
                                    cmbPlanReoccurrence.Text);
                                // Check how many records was deleted
                                if (nRecordsDeleted > 0) // One or more
                                {
                                    lblBankMsg.Text = "Delete plan record is successfully. Deleted " +
                                        nRecordsDeleted.ToString() + " records";
                                    SetPlansGrid();
                                }
                                else // No record deleted
                                {
                                    lblBankMsg.Text = "No plan's record found to delete.";
                                    lblBankMsg.ForeColor = Color.Red;
                                }
                            }
                            else // Plane record closed
                            {
                                string strCantDeleteMSG = "Plan is closed. Cant delete closed plan. Reopen and then delete.";
                                MessageBox.Show(strCantDeleteMSG);
                                lblBankMsg.Text = strCantDeleteMSG;
                            }
                        }
                        else
                        {
                            lblBankMsg.Text = "Cant delete plan record. Input is invalid";
                            lblBankMsg.ForeColor = Color.Red;
                        }
                    }
                }
                else // no plan records selected or selected more than on
                {
                    lblBankMsg.Text = "Choose one plan record to delete.";
                }
            }
            catch
            {
                lblBankMsg.Text = "Delete plan record is failed";
                lblBankMsg.ForeColor = Color.Red;
            }

            SetPlansGrid();
        }
        private void dgvPlans_CellClick(object sender, DataGridViewCellEventArgs e)
        {
            if (dgvPlans.SelectedRows.Count == 1)
            {
                dtPlanDate.Value = (DateTime)dgvPlans.SelectedCells[0].Value;
                //cmbPlanSource.Items.Add(dgvPlans.SelectedCells[2].Value.ToString());
                //cmbPlanSource.SelectedText = "";
                string strNewPlanSource = dgvPlans.SelectedCells[1].Value.ToString();
                if (!cmbPlanSource.Items.Contains(strNewPlanSource))
                {
                    cmbPlanSource.Items.Add(strNewPlanSource);
                    cmbPlanSource.SelectedItem = strNewPlanSource;
                }
                else // Source exist in the combo sources
                {
                    cmbPlanSource.SelectedItem = strNewPlanSource;
                }
                //cmbPlanSource.SelectedText = dgvPlans.SelectedCells[2].Value.ToString();
                txtPlanIn.Text = dgvPlans.SelectedCells[2].Value.ToString();
                txtPlanOut.Text = dgvPlans.SelectedCells[3].Value.ToString();

                string strNewPlanReoccurrence = dgvPlans.SelectedCells[4].Value.ToString();
                //if (!cmbPlanReoccurrence.Items.Contains(strNewPlanReoccurrence))
                //{
                //    cmbPlanReoccurrence.Items.Add(strNewPlanReoccurrence);
                //    cmbPlanReoccurrence.SelectedIndex = 0;
                //}

                cmbPlanReoccurrence.SelectedItem = strNewPlanReoccurrence;

                // Set the expiration date
                long nPlanID = (long)dgvPlans.SelectedCells[6].Value;
                string strStatus = (string)dgvPlans.SelectedCells[5].Value.ToString();
                dtEpirationChoose.Value = Util.GetExpirationDate(nPlanID, strBankName, strNewPlanSource,
                    strNewPlanReoccurrence, strStatus);
            }
        }

        private bool ValidatePlanToDelete()
        {
            bool bValid = true;
            //string strinvalidMessage = "NoMessage";
            
            if (String.IsNullOrEmpty(cmbPlanSource.Text))
            {
                bValid = false;
            }
            else if (cmbPlanReoccurrence.SelectedIndex < 0)
            {
                bValid = false;
            }
            else if (String.IsNullOrEmpty(cmbPlanReoccurrence.Text))
            {
                bValid = false;
            }

            return bValid;
        }

        private void dgvPlans_CellDoubleClick(object sender, DataGridViewCellEventArgs e)
        {
            DateTime dtSelectedDate = (DateTime)dgvPlans.SelectedCells[0].Value;
            string strSelectedSource = (string)dgvPlans.SelectedCells[1].Value.ToString();
            Decimal dSelectedIn = (Decimal)dgvPlans.SelectedCells[2].Value;
            Decimal dSelectedOut = (Decimal)dgvPlans.SelectedCells[3].Value;
            string strStatus = (string)dgvPlans.SelectedCells[5].Value.ToString();
            long nPlanID = (long)dgvPlans.SelectedCells[6].Value;
            
            string strMessageBox = "";
            string strSumToClose = "0";
            Decimal dNewOutInput = 0;
            bool bIfToClose = true;

            try
            {
                if (strStatus.ToUpper() == Util.PLAN_NOT_CLOSED) // Plan not closed
                {
                    //strMessageBox = "Choose sum to close.";
                    
                    strSumToClose = Microsoft.VisualBasic.Interaction.InputBox("Enter sum to close","Closing plan record",
                        dSelectedOut.ToString(),150,150);
                    // Check what user choosed: OK/Cancel
                    if (string.IsNullOrEmpty(strSumToClose)) // Cancel
                    {
                        // Do nothing
                    }
                    else // OK
                    {
                        dNewOutInput = Decimal.Parse(strSumToClose);

                        // Check if the wanted sum is bigger or equel to the record sum (out)
                        if (dNewOutInput >= dSelectedOut) // Need to close this record
                        {
                            bIfToClose = true;
                            strMessageBox = "Are you sure you want to close the plan, Date: " +
                            dtSelectedDate.ToString() + " Source: " + strSelectedSource + " In: " +
                            dSelectedIn.ToString() + " Out: " + dNewOutInput.ToString() + 
                            " from " + dSelectedOut.ToString() + " ?";
                        }
                        else // Record stil open
                        {
                            bIfToClose = false;
                            strMessageBox = "Are you sure you want to close part of the plan, Date: " +
                            dtSelectedDate.ToString() + " Source: " + strSelectedSource + " In: " +
                            dSelectedIn.ToString() + " Out: " + dNewOutInput.ToString() +
                            " from " + dSelectedOut.ToString() + " ?";
                        }
                    }
                }
                else // Plan closed
                {
                    strMessageBox = "This plan closed. Are you sure you want to reopen the plan.";
                }
                DialogResult dl = MessageBox.Show(strMessageBox,
                            "Closing/Opening plan record",
                            MessageBoxButtons.OKCancel);

                if (dl == DialogResult.OK)
                {
                    if (strStatus.ToUpper() == Util.PLAN_NOT_CLOSED) // Plan not closed
                    {
                        DialogResult dl2 = MessageBox.Show("Do you want to use plan date? \n" +
                            "Yes: Plan date \n" +
                            "No: Now date",
                          "Choose date",
                          MessageBoxButtons.YesNoCancel);
                        
                        if (dl2 == DialogResult.Yes) // Plan date
                        {
                            // Insert new bill record
                            bool bIfSuccessSave = SaveNewBill(dtSelectedDate, dSelectedIn, dNewOutInput,
                                Util.GetNewBankID(strBankName), strSelectedSource);

                            if (bIfSuccessSave)
                            {
                                // Recorder the balances in the bills and get the last balance
                                Decimal nFinalBalance = Util.RunOrderBills(Program.GetUserID(), Util.GetNewBankID(strBankName));
                                // Update balances table with the last balance
                                Util.SaveNewBalance(Program.GetUserID(), Util.GetNewBankID(strBankName), nFinalBalance);

                                lblBankMsg.Text = "Saved successfully - bill record";
                                SetBankGrid();
                                // Update DB to Closed: YES/NO
                                // Check if need to Close
                                if (bIfToClose) // Close
                                {
                                    OpenPlanUpdate(nPlanID, dSelectedOut - dNewOutInput, Util.PLAN_CLOSED);
                                }
                                else // Open
                                {
                                    OpenPlanUpdate(nPlanID,dSelectedOut - dNewOutInput, Util.PLAN_NOT_CLOSED);
                                }
                            }
                            else
                            {
                                lblBankMsg.Text = "Unable to save - bill record";
                            }
                        }
                        else if (dl2 == DialogResult.No) // Now date
                        {
                            // Insert new bill record
                            bool bIfSuccessSave = SaveNewBill(DateTime.Now, dSelectedIn, dNewOutInput,
                                Util.GetNewBankID(strBankName), strSelectedSource);
                            if (bIfSuccessSave)
                            {
                                // Recorder the balances in the bills and get the last balance
                                Decimal nFinalBalance = Util.RunOrderBills(Program.GetUserID(), Util.GetNewBankID(strBankName));
                                // Update balances table with the last balance
                                Util.SaveNewBalance(Program.GetUserID(), Util.GetNewBankID(strBankName), nFinalBalance);

                                lblBankMsg.Text = "Saved successfully - bill record";
                                SetBankGrid();
                                // Update DB to Closed: YES/NO
                                // Check if need to Close
                                if (bIfToClose) // Close
                                {
                                    OpenPlanUpdate(nPlanID,dSelectedOut - dNewOutInput, Util.PLAN_CLOSED);
                                }
                                else // Open
                                {
                                    OpenPlanUpdate(nPlanID, dSelectedOut - dNewOutInput,Util.PLAN_NOT_CLOSED);
                                }
                            }
                            else
                            {
                                lblBankMsg.Text = "Unable to save - bill record";
                            }
                        }
                        else if (dl2 == DialogResult.Cancel) // Cancel
                        {
                        }
                    }
                    else // Plan closed
                    {
                        OpenPlanUpdate(nPlanID, Util.PLAN_NOT_CLOSED);
                    }
                    SetPlansGrid();
                }
            }
            catch
            {
                lblBankMsg.Text = lblBankMsg.Text + ". Problem to close plan.";
            }
        }
        private bool SaveNewBill(DateTime dtDate, Decimal lIn, Decimal lOut, long lBankID, string strSource)
        {
            bool bIsSuccess = true;
            try
            {
                // Invoke the save bill record function
                Util.SaveRecord(Program.GetUserID(), dtDate, lIn, lOut,
                    lBankID, strSource);
            }
            catch
            {
                bIsSuccess = false;
            }

            return bIsSuccess;
        }
        private void OpenPlanUpdate(long lPlanID, string strStatus)
        {
            HBADBDataContext dbCon = new HBADBDataContext();
            Plan openPlan = dbCon.Plans.Single(p => p.PlanID == lPlanID);
            openPlan.Closed = strStatus;
            
            dbCon.SubmitChanges();
        }
        private void OpenPlanUpdate(long lPlanID, Decimal dNewOut, string strStatus)
        {
            HBADBDataContext dbCon = new HBADBDataContext();
            Plan openPlan = dbCon.Plans.Single(p => p.PlanID == lPlanID);
            openPlan.Closed = strStatus;
            openPlan.OutSum = dNewOut;

            dbCon.SubmitChanges();
        }

        private void SumPlanNo()
        {
            try
            {
                using (HBADBDataContext db = new HBADBDataContext())
                {
                    Decimal nSumPlanNo = 0;
                    foreach (var record in db.Plans)
                    {
                        if (record.Date < new DateTime(DateTime.Now.Year, DateTime.Now.Month, 1, 0, 0, 0).AddMonths(Util.ADD_TO_CURR_MONTH) &&
                            record.Date >= new DateTime(DateTime.Now.Year, DateTime.Now.Month, 1, 0, 0, 0).AddMonths(Util.ADD_TO_CURR_MONTH - 1) &&
                            record.UserID == Program.GetUserID() &&
                            record.BankID == Util.GetNewBankID(strBankName) &&
                            record.Closed == Util.PLAN_NOT_CLOSED)
                        {
                            nSumPlanNo = nSumPlanNo + record.OutSum - record.InSum;
                        }
                    }

                    // Set text box with the sum number
                    txtSumPlanNo.Text = nSumPlanNo.ToString();

                    lblBankMsg.Text = "All OK";
                    lblBankMsg.ForeColor = Color.Green;
                }
            }
            catch
            {
                lblBankMsg.Text = "Sum plan refresh failed";
                lblBankMsg.ForeColor = Color.Red;
            }

        }

        private void ShowCurrMontSumPlan()
        {
            try
            {
                txtSumForMonth.Text = Microsoft.VisualBasic.DateAndTime.MonthName(DateTime.Now.AddMonths(-1).AddMonths(Util.ADD_TO_CURR_MONTH).Month);

                lblBankMsg.Text = "All OK";
                lblBankMsg.ForeColor = Color.Green;
            }
            catch
            {
                lblBankMsg.Text = "Show for current month sum plan failed";
                lblBankMsg.ForeColor = Color.Red;
            }
        }
        private void btnRefreshSumPlan_Click(object sender, EventArgs e)
        {
            DoRefreshSumPlan();
        }

        private void DoRefreshSumPlan()
        {
            SumPlanNo();
            ShowCurrMontSumPlan();
            ShowExpectedBalance();
        }

        private void btnNextMonthSum_Click(object sender, EventArgs e)
        {
            Util.ADD_TO_CURR_MONTH++;
            ShowCurrMontSumPlan();
        }

        private void btnPrevMonthSum_Click(object sender, EventArgs e)
        {
            Util.ADD_TO_CURR_MONTH--;
            ShowCurrMontSumPlan();
        }

        private void ShowExpectedBalance()
        {
            try
            {
                HBADBDataContext db = new HBADBDataContext();

                var query = (from balance in db.Balances
                            join bank in db.Banks on balance.BankID equals bank.BankID
                            where balance.UserID == Program.GetUserID() &&
                            balance.BankID == Util.GetNewBankID(strBankName)
                            select new { CurrentBalance = balance.CurrentBalance }).Single();
                //MessageBox.Show(query.CurrentBalance.ToString());

                txtExpectedBalance.Text = (query.CurrentBalance - Decimal.Parse(txtSumPlanNo.Text)).ToString();

                lblBankMsg.Text = "All OK";
                lblBankMsg.ForeColor = Color.Green;
            }
            catch
            {
                lblBankMsg.Text = "Show expected balance failed";
                lblBankMsg.ForeColor = Color.Red;
            }
         }
    }
}
